import torch
from torch import nn
from d2l import torch as d2l

n_train = 50  # 训练样本数
x_train, _ = torch.sort(torch.rand(n_train) * 5)  # 排序后的训练样本
from heatmaps import show_heatmaps


def f(x):
    return 2 * torch.sin(x) + x ** 0.8


y_train = f(x_train) + torch.normal(0.0, 0.5, (n_train,))  # 训练样本的输出
x_test = torch.arange(0, 5, 0.1)  # 测试样本
# print(x_test,"111111111")
y_truth = f(x_test)  # 测试样本的真实输出
n_test = len(x_test)  # 测试样本数
print(x_test)
print(n_test)


def plot_kernel_reg(y_hat):
    d2l.plot(x_test, [y_truth, y_hat], 'x', 'y', legend=['Truth', 'Pred'],
             xlim=[0, 5], ylim=[-1, 5])
    # x_train是0-5之间随机取x轴上n个点，y_train是x_train对应的观测值
    d2l.plt.plot(x_train, y_train, 'o', alpha=0.5)
    d2l.plt.show()


# 变种的那达拉亚沃特森模型
class NWKernelRegression(nn.Module):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 定义一个参数
        self.w = nn.Parameter(torch.rand((1,), requires_grad=True))

    def forward(self, queries, keys, values):
        # queries和attention_weights的形状为(查询个数，“键－值”对个数)
        # print("queries1",queries)
        queries = queries.repeat_interleave(keys.shape[1]).reshape((-1, keys.shape[1]))
        print("queries2", queries)
        print("keys", keys)
        print("values", values)
        self.attention_weights = nn.functional.softmax(
            -((queries - keys) * self.w) ** 2 / 2, dim=1)
        print("attr shape", self.attention_weights.shape)
        # values的形状为(查询个数，“键－值”对个数)
        return torch.bmm(self.attention_weights.unsqueeze(1),
                         values.unsqueeze(-1)).reshape(-1)


# # X_tile的形状:(n_train，n_train)，每一行都包含着相同的训练输入
# X_tile = x_train.repeat((n_train, 1))
# # Y_tile的形状:(n_train，n_train)，每一行都包含着相同的训练输出
# Y_tile = y_train.repeat((n_train, 1))
# # keys的形状:('n_train'，'n_train'-1) 每一行去掉当前列的值
# keys = X_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
# # values的形状:('n_train'，'n_train'-1) 每一行去掉当前列的值
# values = Y_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))#


# X_tile的形状:(n_train，n_train)，每一行都包含着相同的训练输入
X_tile = x_train.repeat((n_train, 1))
# Y_tile的形状:(n_train，n_train)，每一行都包含着相同的训练输出
Y_tile = y_train.repeat((n_train, 1))
# keys的形状:('n_train'，'n_train'-1) 每一行去掉当前列的值
keys = X_tile
# values的形状:('n_train'，'n_train'-1) 每一行去掉当前列的值
values = Y_tile

print("x_train", x_train)
print("y_train", y_train)
# print("X_tile",X_tile)
# print("Y_tile",Y_tile)
# print("keys",keys)
# print("values",values)

net = NWKernelRegression()
loss = nn.MSELoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=0.5)
animator = d2l.Animator(xlabel='epoch', ylabel='loss', xlim=[1, 5])

for epoch in range(50):
    trainer.zero_grad()
    l = loss(net(x_train, keys, values), y_train)
    l.sum().backward()
    trainer.step()
    print(f'epoch {epoch + 1}, loss {float(l.sum()):.6f}')
    animator.add(epoch + 1, float(l.sum()))

# keys的形状:(n_test，n_train)，每一行包含着相同的训练输入（例如，相同的键）
keys = x_train.repeat((n_test, 1))
# value的形状:(n_test，n_train)
values = y_train.repeat((n_test, 1))
print("_____________________________________________________________")
y_hat = net(x_test, keys, values).unsqueeze(1).detach()
plot_kernel_reg(y_hat)

show_heatmaps(net.attention_weights.unsqueeze(0).unsqueeze(0),
              xlabel='Sorted training inputs',
              ylabel='Sorted testing inputs')

"""
x_train tensor([2.4090, 2.6749, 3.3800, 3.4999, 4.4537])
y_train tensor([2.5830, 3.5373, 3.2864, 2.1439, 1.2284])

queries tensor([[2.4090, 2.4090, 2.4090, 2.4090],
        [2.6749, 2.6749, 2.6749, 2.6749],
        [3.3800, 3.3800, 3.3800, 3.3800],
        [3.4999, 3.4999, 3.4999, 3.4999],
        [4.4537, 4.4537, 4.4537, 4.4537]])
keys tensor([[2.6749, 3.3800, 3.4999, 4.4537],
        [2.4090, 3.3800, 3.4999, 4.4537],
        [2.4090, 2.6749, 3.4999, 4.4537],
        [2.4090, 2.6749, 3.3800, 4.4537],
        [2.4090, 2.6749, 3.3800, 3.4999]])
values tensor([[3.5373, 3.2864, 2.1439, 1.2284],
        [2.5830, 3.2864, 2.1439, 1.2284],
        [2.5830, 3.5373, 2.1439, 1.2284],
        [2.5830, 3.5373, 3.2864, 1.2284],
        [2.5830, 3.5373, 3.2864, 2.1439]])
"""
